// store/modules/order.js
import axios from 'axios';
import router from "@/router";

export default {
    namespaced: true,
    state: {
        orderInfo: null,
        error: null,
        orders: [],
        orderPagination: {
            currentPage: 1,
            pageSize: 5,
            total: 0
        },
        type: 0,
    },
    mutations: {
        SET_ORDER_INFO(state, orderInfo) {
            state.orderInfo = orderInfo;
        },
        SET_ERROR(state, error) {
            state.error = error;
        },
        SET_TYPE(state, type) {
            state.type = type;
        },
        SET_ORDERS(state, orders) {
            state.orders = orders;
        },
        SET_ORDER_PAGE_SIZE(state, size) {
            state.orderPagination.pageSize = size
        },
        SET_ORDER_CURRENT_PAGE(state, page) {
            state.orderPagination.currentPage = page
        },
        SET_ORDER_TOTAL(state, total) {
            state.orderPagination.total = total
        },
    },
    actions: {
        async createOrder({ commit }, orderData) {
            try {
                const response = await axios.post('order/api/order/create/travel', orderData);

                if (response.data.code === 200) {
                    commit('SET_ORDER_INFO', {
                        orderNo: response.data.data.orderNo,
                        orderId: response.data.data.orderId,
                    });
                    return { success: true };
                } else {
                    commit('SET_ERROR', response.data.message || '订单创建失败');
                    return { success: false, error: response.data.message || '订单创建失败' };
                }
            } catch (error) {
                console.error('订单创建失败:', error);
                const errorMessage = '订单创建失败，请稍后再试';
                commit('SET_ERROR', errorMessage);
                return { success: false, error: errorMessage };
            }
        },
        async fetchOrders({ commit, state }) {
            try {
                console.log(state)
                const response = await axios.get(`order/api/order/list/travel`, {
                    params: {
                        type: state.type,
                        page: state.orderPagination.currentPage,
                        limit: state.orderPagination.pageSize,
                    }
                });
                if (response.data.code === 200) {
                    commit('SET_ORDERS', response.data.data.list);
                    commit('SET_ORDER_TOTAL',response.data.data.total)
                    commit('SET_ORDER_CURRENT_PAGE',response.data.data.page)
                    commit('SET_ORDER_PAGE_SIZE',response.data.data.limit)
                } else if (response.data.code === 401 && response.data.message === "登录信息已过期，请重新登录！"){
                    await router.push("/login")
                }else {
                    throw new Error(response.data.message || '获取订单失败');
                }
            } catch (error) {
                console.error('获取订单失败:', error);
                throw error;
            }
        },
        async fetchOrderDetails(_, id) {
            try {
                const response = await axios.get(`order/api/order/detail/travel/id/${id}`);
                if (response.data.code === 200) {
                    return response.data.data;
                } else if (response.data.code === 308 && response.data.message === '订单已失效'){
                    throw new Error(response.data.message || '订单已失效');
                }else {
                    throw new Error(response.data.message || '获取订单详情失败');
                }
            } catch (error) {
                console.error('获取订单详情失败:', error);
                throw error;
            }
        },
        async cancelOrder(_,orderId) {
            try {
                const formData = new FormData();
                formData.append('id', orderId);
                const response = await axios.post('order/api/order/cancel', formData);

                if (response.data.code === 200) {
                    return true;
                } else if (response.data.code === 401 && response.data.message === "登录信息已过期，请重新登录！"){
                    await router.push("/login");
                } else {
                    throw new Error(response.data.message || '取消订单失败');
                }
            } catch (error) {
                console.error('取消订单失败:', error);
                throw error;
            }
        },
        async cancelApplication(_,orderId) {
            try {
                const formData = new FormData();
                formData.append('id', orderId);
                const response = await axios.post('order/api/order/cancel-application', formData);

                if (response.data.code === 200) {
                    return true;
                } else if (response.data.code === 401 && response.data.message === "登录信息已过期，请重新登录！"){
                    await router.push("/login");
                } else {
                    throw new Error(response.data.message || '取消申请失败');
                }
            } catch (error) {
                console.error('取消申请失败:', error);
                throw error;
            }
        },
        async takeOrder(_,orderId) {
            try {
                const formData = new FormData();
                formData.append('id', orderId);
                const response = await axios.post('order/api/order/take', formData);

                if (response.data.code === 200) {
                    return true;
                } else if (response.data.code === 401 && response.data.message === "登录信息已过期，请重新登录！"){
                    await router.push("/login");
                } else {
                    throw new Error(response.data.message || '消费失败');
                }
            } catch (error) {
                console.error('消费失败:', error);
                throw error;
            }
        },
        async refundOrder(_,refundOrderData) {
            try {
                const response = await axios.post('order/api/order/refund', refundOrderData);

                if (response.data.code === 200) {
                    return true;
                } else if (response.data.code === 401 && response.data.message === "登录信息已过期，请重新登录！"){
                    await router.push("/login");
                } else {
                    throw new Error(response.data.message || '退款失败');
                }
            } catch (error) {
                console.error('退款失败:', error);
                throw error;
            }
        },
    },
    getters: {
        getOrderInfo: state => state.orderInfo,
        getError: state => state.error,
        getOrders: state => state.orders,
        getType: state => state.type,
    },
};
